package com.passion.mq.aspect;

import com.passion.common.context.SpringContextUtil;
import com.passion.common.threadpool.MyCompletableFuture;
import com.passion.common.threadpool.ThreadPoolHelper;
import com.passion.common.util.StringUtils;
import com.passion.mq.annotation.AsyncMQ;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 类描述：@AsyncMQ注解的切面逻辑
 *
 * @author ZhuYin
 * @since 2024年12月29日
 */
@Slf4j
@Aspect
@Component
public class AsyncMqAspect {

    @Around("@annotation(asyncMQ) || @within(asyncMQ)")
    public Object around(ProceedingJoinPoint joinPoint, AsyncMQ asyncMQ) throws Throwable {
        // 获取目标对象
        Object target = joinPoint.getTarget();
        // 获取线程池名称
        String executorName = asyncMQ.executor();
        ThreadPoolExecutor executor = ThreadPoolHelper.asyncLogTaskThreadPool;
        if (StringUtils.isNotBlank(executorName)) {
            executor = SpringContextUtil.getBean(executorName);
        }
        if (executor != null) {
            String executorInfo = executor.toString();
            // 提交任务到线程池
            return MyCompletableFuture.supplyAsync(() -> {
                // 执行目标方法
                try {
                    log.info("线程池[{}]异步执行MQ发送任务开始", executorInfo);
                    // 执行目标方法
                    Object result = joinPoint.proceed();
                    log.info("线程池[{}]异步执行MQ发送任务结束", executorInfo);
                    return result;
                } catch (Throwable e) {
                    throw new RuntimeException(e);
                }
            }, executor);
        }
        return joinPoint.proceed();
    }
}
